package com.visionblue.business.ship.service

import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import android.widget.Toast
import com.visionblue.business.ship.ext.toast
import com.visionblue.business.ship.model.bean.local.PrintInfo
import com.visionblue.business.ship.print.PrintException
import com.visionblue.business.ship.print.PrintManager
import kotlinx.coroutines.*

/**
 * @author: xlh
 * @date: 2020-06-17 6:35 PM
 * @desc:
 */
class PrintService : Service(), CoroutineScope by MainScope() {

    private var printJob: Job? = null

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val printInfo = intent?.getParcelableExtra<PrintInfo>(PRINT_INFO)
        if (printInfo != null) {
            if (printJob != null) {
                Toast.makeText(this@PrintService, "打印机正在作业中", Toast.LENGTH_SHORT).show()
                return super.onStartCommand(intent, flags, startId)
            }

            printJob = launch(Dispatchers.IO) {
                try {
                    PrintManager.getInstance(this@PrintService).startPrint(printInfo)
                } catch (e: PrintException) {
                    withContext(Dispatchers.Main) {
                       toast { e.message }
                    }
                } finally {
                    printJob = null
                }
            }
        }

        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
        super.onDestroy()
        printJob = null
        cancel()
    }

    companion object {

        private const val PRINT_INFO = "printInfo"

        fun start(context: Context, printInfo: PrintInfo) {
            context.startService(Intent(context, PrintService::class.java).apply {
                putExtra(PRINT_INFO, printInfo)
            })
        }
    }
}